package it.example.pad;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
/*
 * Classe che gestisce la comunicazione con il server
 */
public class Driver {
	private static Driver driver=null;
	public static final String BUTTON_DOWN_SX = "sxdown";
	public static final String BUTTON_DOWN_DX = "dxdown";
	public static final String BUTTON_UP_SX = "sxup";
	public static final String BUTTON_UP_DX = "dxup";
	private static final String MOVE = "move";
	private static final String OK = "OK";
	private static final String CONNECT = "connect";
	private DatagramSocket s;
	private String ip;
	private int port;
	
	public void sendClick(String command) {
		
		
		try {
			String string = command+"#1#1##";
			byte[] bytes=string.getBytes();
			InetAddress address;
			address = InetAddress.getByName(ip);
			DatagramPacket dp = new DatagramPacket(bytes, bytes.length,address,port);
			s.send(dp);
		} catch (Exception e) {
			closeConnection();
			e.printStackTrace();
		}
	}

	public void sendMove(int dx, int dy) {
			String string = MOVE+"#"+dx+"#"+dy+"##";
			byte[] bytes=string.getBytes();
			try {
				InetAddress address;
				address = InetAddress.getByName(ip);
				DatagramPacket dp = new DatagramPacket(bytes, bytes.length,address,port);
				s.send(dp);
			} catch (Exception e) {
				e.printStackTrace();
				closeConnection();
			}
	}
	
	/*
	 * il protocollo UDP non prevede la connessione. Questo metodo ha quindi lo scopo di verificare la presenza del server in
	 * ascolto e comunicare ad esso il DPI dello smartphone
	 */
	public void connect(String ip, int port, int dpi) throws IOException, InterruptedException, SocketException {
			s=new DatagramSocket();
			this.ip=ip;
			this.port=port;
			String string = CONNECT+"#"+dpi+"#"+s.getLocalPort()+"##";
			//Log.d("AAAA", "port "+s.getLocalPort());
			byte[] bytes=string.getBytes();
			InetAddress address;
			address = InetAddress.getByName(ip);
			DatagramPacket dp = new DatagramPacket(bytes, bytes.length,address,port);
			s.send(dp);
			byte data[]=new byte[10];
			DatagramPacket packet=new DatagramPacket(data,data.length);
			s.setSoTimeout(3000);					//setto il timeout sulla ricezione dell'ACK a 3 secondi
			s.receive(packet);						//aspetto l'arrivo dell'ack
			String mex = new String(packet.getData(), 0, packet.getLength());
			if(mex.compareTo(OK)!=0)
				throw new IOException();			

	}
	public void closeConnection(){
		if(s!=null)
				s.close();
			
	}

	/*
	 * ---- PATTERN SINGLETON ----
	 */
	public static Driver getDriver() {
		if(driver==null)
			driver = new Driver();
			return driver;
	}
	
	

}
